/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.core.session;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyandong
 */
@Slf4j
public class BackendSessionHolder implements CafSessionHolder {
    /**
     * 返回匹配的Session类型
     */
    @Override
    public List<SessionType> getMatchingSessionTypes() {
        List<SessionType> list = new ArrayList<>();
        list.add(SessionType.backend);
        return list;
    }

    /**
     * 获取当前的Session对象
     */
    @Override
    public CafSession getCurrentSession() {
        return CafSessionThreadHolder.getCurrentSession();
    }

    @Override
    public CafSession getCopyedCurrentSession() {
        return getCurrentSession();
    }

    /**
     * 获取当前的Session对象
     */
    @Override
    public void setCurrentSession(CafSession session) {
        if (log.isDebugEnabled()) {
            log.debug("设置backend session，ThreadName={}，sessionId={}", Thread.currentThread().getName(), session != null ? session.getId() : null, new Exception());
        }

        CafSessionThreadHolder.setCurrentSession(session);
    }

    @Override
    public void setCurrentThreadPoolSession(CafSession session) {
        if (log.isDebugEnabled()) {
            log.debug("设置backend ThreadPool session，ThreadName={}，sessionId={}", Thread.currentThread().getName(), session != null ? session.getId() : null, new Exception());
        }

        CafSessionThreadHolder.setCurrentSession(session);
    }

    /**
     * 清理当前Session
     */
    @Override
    public void clear() {
        if (log.isDebugEnabled()) {
            CafSession currentSession = CafSessionThreadHolder.getCurrentSession();
            log.debug("清理backend session，ThreadName={}，sessionId={}", Thread.currentThread().getName(), currentSession != null ? currentSession.getId() : null, new Exception());
        }

        CafSessionThreadHolder.purge();
    }

    @Override
    public void clearCurrentThreadPoolSession() {
        if (log.isDebugEnabled()) {
            CafSession currentSession = CafSessionThreadHolder.getCurrentSession();
            log.debug("清理backend ThreadPool session，ThreadName={}，sessionId={}", Thread.currentThread().getName(), currentSession != null ? currentSession.getId() : null, new Exception());
        }

        CafSessionThreadHolder.purge();
    }
}
